<?php
/**
 * Created by PhpStorm
 * User: huangjiacheng
 * Date: 2023/6/5
 * Time: 13:51
 */

namespace app\command;


use think\facade\Db;
use think\console\input\Option;
use think\console\Command;
use think\facade\Console;
use think\console\Output;
use think\console\Input;


class SelectCode extends Command
{
    protected function configure()
    {
        $this->setName('select:code')
            ->addOption('min', null, Option::VALUE_REQUIRED, '最小值')
            ->addOption('max', null, Option::VALUE_REQUIRED, '最大值')
            ->addOption('config', null, Option::VALUE_REQUIRED, '第几梯队')
            ->setDescription('筛选code信息脚本');
    }
    protected $myConfig = [
        'licence' => '240173e804a5948d95',
        'ssjy' => 'https://api.mairuiapi.com/hsrl/ssjy', //  实时交易
        'macd' => 'https://api.mairuiapi.com/hszb/macd/',
        'rsi'	=> '',
        'config' => [
            1 => [
                'qywx' => 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=19d0274f-23d2-4e8b-a301-a72035577f50',
                'trade_table' =>  'trade_code',
                'date_table' =>  'zj_info_date',
                'min_yuer'  =>  30000,  //不满仓，保留余额
                'max_buy_price' => 100, // 最多价格
                'per_buy'   =>  10000,  //每次购买最大价格
            ],
            2 => [
                'qywx' => 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=538e972d-b83b-4c8e-8eb0-7e857dc95637',
                'trade_table' =>  'trade_two_code',
                'date_table' =>  'zj_two_info_date',
                'min_yuer'  =>  15000,
                'max_buy_price' => 50,
                'per_buy'   =>  5000,  //每次购买最大价格
            ],

        ],
    ];
    protected function execute(Input $input, Output $output)
    {
        $output->info('这是筛选code信息脚本');

        $min = $input->getOption('min');
        $max = $input->getOption('max');
        $config = array_keys($this->myConfig['config']);

        $today  = date("Y-m-d");
        $sql = "select * from holiday where holiday>='$today' ";
        $list = Db::query($sql);
        $holiday_list = array_column($list,'holiday');
        if (in_array($today,$holiday_list)){
            $output->info('today is holiday');
            return ;
        }

        $sql = "select * from base_info where ltsz >=$min and ltsz<=$max and  code like '3%' ";
        $list = Db::query($sql);
        $msg = [];

        foreach ($list as $row) {
            try {
                $code = $row['code'];
                $url = $this->myConfig['ssjy'] . "/" . $code . "/" . $this->myConfig['licence'];
                $str = file_get_contents($url);
                sleep(2);
                $data = json_decode($str, true);
                if (empty($data['sz'])) {
                    $i = 0;
                    while (1) {
                        $url = $this->myConfig['ssjy'] . "/" . $code . "/" . $this->myConfig['licence'];
                        $str = file_get_contents($url);
                        sleep(1);
                        $data = json_decode($str, true);
                        if (!empty($data['sz'])) {
                            break;
                        }
                        if ($i > 100) {
                            break;
                        }
                        $i++;
                    }
                }
                /** 选股逻辑
                 *  自动筛选逻辑
                 *  1.市值50亿到200亿  (done)
                 *  2.量比大于1，资金流入(done)
                 *  3.换手率 5%-10%(done)
                 *  4.当日涨幅14:30之后在 3-5%(done)
                 *  5.macd 大于0 且 diff 大于0
                 *  6.RSI 大于50 且小于80
                 *  7.PE>1(done),去除亏损数据
                 *  人工筛选逻辑
                 *  1.看K线成交量持续放大
                 */
                if (
                    ($data['lb'] > 1) &&
                    ($data['hs'] > 5 and $data['hs'] < 10) &&
                    ($data['pc'] > 3 and $data['pc'] < 5) &&
                    ($data['pe'] > 1)
                ) {
                    $date = date("Y-m-d");
                    $lb = $data['lb'];
                    $hs = $data['hs'];
                    $pc = $data['pc'];
                    $sz = $data['sz'];
                    $macd_url= $this->myConfig['macd'].$code.'/dn/'.$this->myConfig['licence'];
              
                    $str=file_get_contents($macd_url);
                    $macd_data =json_decode($str,true);
                    //macd 判断
                    if (!empty($macd_data['macd'])) {
                        if (($macd_data['macd'] > 0)) {
                            $msg[] = $code;
                            echo $code;
                            foreach ($config as $key => $value) {
                                $this->buyCode($code, $data['p'],$value);
                            }
                        }
                    }
                    // $msg[] = $code;
                    $insert = "replace into sel_code(`code`,`lb`,`hs`,`pc`,`sz`,`date`) values('$code','$lb','$hs','$pc','$sz','$date')";
                    Db::query($insert);
                    
                    
                    
                }
            }catch (\Exception $e) {
                echo $e;
            }
        }

        $msg_str = implode("\n", $msg);
        foreach ($config as $key => $value) {                
            $this->alarm($msg_str,$min,$max,$value);
        }
      
    }

    protected function alarm($msg,$min,$max,$config){
        $webhook = $this->myConfig['config'][$config]['qywx'];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $webhook);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json;charset=utf-8'));
        $post_data = [
            'msgtype' => 'text',
            'text' => [
                'content' => "【".date("Y-m-d H:i:s")."】【".($min/100000000)."-".($max/100000000)."推荐代码】\n".$msg,
            ]
        ];
        $post_data = json_encode($post_data);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        $data = curl_exec($curl);
        curl_close($curl);
    }


    protected function buyCode($code,$price,$config){
        $sql = "select * from zj_info where id =$config ";
        $list = Db::query($sql);
        $row = $list[0];
        if ($row['yuer'] < $this->myConfig['config'][$config]['min_yuer']) {
            return false;
        }else{
            if ($price >= $this->myConfig['config'][$config]['max_buy_price']) {
                return false;
            }
            $num = intval($this->myConfig['config'][$config]['per_buy']/($price*100)); //
            $buy_num = 100 *$num;
            $buy_date = date("Y-m-d");
            // $buy_date = date("Y-m-d",strtotime("+1 day"));
            $insert="insert into ".$this->myConfig['config'][$config]['trade_table']." (`code`,`buy`,`buy_num`,`buy_date`,`sell`) 
				values('$code','$price','$buy_num','$buy_date','0')";
            Db::query($insert);

            $yuer = $row['yuer'] - ($price*$buy_num);
            $chicang = $row['chicang'] + ($price*$buy_num);
            $update = "update zj_info set yuer = '$yuer',chicang='$chicang'  where id=$config";
            Db::query($update);

            $msg = $code.'|'.$price."|".$buy_num;
            $webhook = $this->myConfig['config'][$config]['qywx'];
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $webhook);
            curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json;charset=utf-8'));
            $post_data = [
                'msgtype' => 'text',
                'text' => [
                    'content' => "【buy:".date("Y-m-d H:i:s")."】\n".$msg,
                ]
            ];
            $post_data = json_encode($post_data);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
            $data = curl_exec($curl);
            curl_close($curl);
        }

    }
}